package com.itheima.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.RegisteredPayload;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.itheima.dto.MediaUserDto;
import com.itheima.mapper.UserMapper;
import com.itheima.po.MediaUser;
import com.itheima.service.UserService;
import com.itheima.vo.MediaUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author :wujunjie
 * createTime :2023-01-02 16:55
 * description :
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public MediaUserVo login(MediaUserDto dto) {
        MediaUser mediaUser = new MediaUser();
        BeanUtils.copyProperties(dto,mediaUser);
        MPJLambdaWrapper<MediaUser> wrapper=new MPJLambdaWrapper<>();
        wrapper.eq(MediaUser::getName,dto.getName());
        wrapper.eq(MediaUser::getPassword, dto.getPassword());
        MediaUser mediaUserInDB = userMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(mediaUserInDB)){
            throw new RuntimeException("账号或密码不对");
        }
        mediaUserInDB.setLoginTime(LocalDateTime.now());
        int i = userMapper.updateById(mediaUserInDB);
        if (i!=1){
            throw new RuntimeException("数据更新失败");
        }

        MediaUserVo mediaUserVo = new MediaUserVo();
        mediaUserInDB.setPassword(null);
        mediaUserVo.setUser(mediaUserInDB);
        mediaUserVo.setToken(getToken(mediaUserInDB.getId()));
        return mediaUserVo;
    }


    private static String getToken(Long id) {
        DateTime now = DateUtil.date();
        DateTime exp = DateUtil.offset(now, DateField.HOUR, 24);
        Map<String,Object> payload=new HashMap<>();
        payload.put(RegisteredPayload.ISSUED_AT,now);
        payload.put(RegisteredPayload.NOT_BEFORE, now);
        payload.put(RegisteredPayload.EXPIRES_AT,exp);
        payload.put("id",id);
        return JWTUtil.createToken(payload, "heimaLeadnews".getBytes());
    }
}
